package com.trade.okxserver.ws;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.trade.okxserver.clr.trade.SubscribeEvent;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.Objects;
import java.util.function.Consumer;

@Slf4j
public class SimpleWebSocketClient<T> extends WebSocketClient {

    private final static Gson GSON = new Gson();

    private Consumer<T> openHandle = null;
    private Consumer<String> messageHandle = null;
    private Consumer<SimpleWebSocketClient> closeHandle = null;
    private Consumer<Exception> errorHandle = null;

    private T t;

    public SimpleWebSocketClient(URI serverUri, Draft draft, T t) {
        super(serverUri, draft);
        this.t = t;
    }

    @Override
    @SneakyThrows
    public void onOpen(ServerHandshake handshakedata) {
//        log.info("创建websocket链接成功");
        if (openHandle != null) {
            openHandle.accept(t);
        }
    }

    @Override
    public void onMessage(String message) {
        SubscribeEvent subscribeEvent = GSON.fromJson(message, SubscribeEvent.class);
        if(Objects.nonNull(subscribeEvent.getEvent())){
            return ;
        }
//        subscribeEvent.getEvent().equals()
//        log.info("接收websocket消息：{}", message);
        if (messageHandle != null) {
            messageHandle.accept(message);
        }
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        log.info("Connection closed by {}, Code: {}, Reason: {}, channel{}", remote ? "remote peer" : "us", code, reason, GSON.toJson(t));
        if (closeHandle != null) {
            closeHandle.accept(this);
        }
    }

    @Override
    public void onError(Exception ex) {
        log.error("websocket异常", ex);
        if (errorHandle != null) {
            errorHandle.accept(ex);
        }
    }

    public Consumer<T> getOpenHandle() {
        return openHandle;
    }

    public void setOpenHandle(Consumer<T> openHandle) {
        this.openHandle = openHandle;
    }

    public Consumer<String> getMessageHandle() {
        return messageHandle;
    }

    public void setMessageHandle(Consumer<String> messageHandle) {
        this.messageHandle = messageHandle;
    }

    public Consumer<SimpleWebSocketClient> getCloseHandle() {
        return closeHandle;
    }

    public void setCloseHandle(Consumer<SimpleWebSocketClient> closeHandle) {
        this.closeHandle = closeHandle;
    }

    public Consumer<Exception> getErrorHandle() {
        return errorHandle;
    }

    public void setErrorHandle(Consumer<Exception> errorHandle) {
        this.errorHandle = errorHandle;
    }

}

